<template>
  <view class="app-container switch-rooms-page">
    <view class="room-list">
      <view class="room-item" v-for="(item,index) in list" :key="item.id" @click="selectRoom(list[index])">
        <view class="room-item__left">
          <view class="name">{{ item.premisesAddress }}</view>
          <view class="address">租住：{{ item.checkInTime }} ~ {{item.checkOutTime}}</view>
        </view>
        <view class="btns" v-if="item.isSelected">
          <u-icon name="checkmark-circle-fill" color="#19be6b"></u-icon>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {houseList} from "@/api/manager/order";
import storage from "@/utils/storage";
import constant from "@/utils/constant";

export default {
  data() {
    return {
      list: []
    };
  },
  created() {
    this.getHouseList()
  },
  methods: {
    selectRoom(item) {
      this.list.forEach((room) => {
        room.isSelected = false;
      });
      // 把当前点击的item的isSelected设置为true
      item.isSelected = true;
      storage.set(constant.room, item);
      // 延迟200毫秒跳转到首页
      setTimeout(() => {
        this.$tab.switchTab('/pages/manager/index');
      }, 200);
    },
    getHouseList: function () {
      houseList().then(res => {
        let data = res.data
        const room = storage.get(constant.room)
        if (room) {
          // 如果有room，则遍历data，找到匹配的item，设置isSelected为true
          data.forEach((item) => {
            if (item.orderId === room.orderId) {
              item.isSelected = true;
            }
          });
        } else {
          // 把第一个room的isSelected设置为true
          if (data.length > 0) {
            data.forEach((room) => {
              room.isSelected = false;
            });
            data[0].isSelected = true;
          }
        }
        // 把isSelected设置为true的item移动到第一个
        data.sort((a, b) => {
          return a.isSelected === b.isSelected ? 0 : a.isSelected ? -1 : 1;
        });
        this.list = data
      })
    }


  }
}
</script>

<style lang="scss">
.switch-rooms-page {
  .room-list {
    padding: 20rpx;

    .room-item {
      display: flex;
      align-items: center;
      padding: 40rpx 20rpx;
      border-radius: 20rpx;
      background-color: #fff;
      margin-bottom: 20rpx;

      .room-item__left {
        flex: 1;

        .address {
          margin-top: 12rpx;
          color: #999;
          font-size: 24rpx;
        }
      }

      .btns {
        width: 100rpx;
        display: flex;
        // 垂直水平居中
        align-items: center;
        justify-content: center;
      }


    }
  }

}

</style>